// cart.js
const api = require('../../utils/api')

Page({
  data: {
    cartList: [],
    allSelected: false,
    totalPrice: 0,
    selectedCount: 0,
    loading: false
  },

  onLoad() {
    // 页面加载时执行一次
    this.loadCartData()
  },

  onShow() {
    // 每次显示页面时都重新加载数据
    const app = getApp()
    // 如果已登录，直接加载数据
    if (app.globalData.isLogin) {
      this.loadCartData()
    } else {
      this.setData({
        cartList: [], // 清空现有数据
        allSelected: false,
        totalPrice: 0,
        selectedCount: 0
      })
      // 检查是否刚刚登录成功（从登录页返回）
      const pages = getCurrentPages()
      const prevPage = pages[pages.length - 2]
      if (prevPage && prevPage.route === 'pages/login/login') {
        // 如果是从登录页返回，等待一下token写入
        setTimeout(() => {
          this.loadCartData()
        }, 100)
      } else {
        this.showLoginModal()
      }
    }
  },

  onHide() {
    // 页面隐藏时清空数据
    this.setData({
      cartList: [],
      allSelected: false,
      totalPrice: 0,
      selectedCount: 0
    })
  },

  // 清空购物车
  async clearCart() {
    try {
      const res = await api.clearCart()
      if (res.success) {
        this.setData({
          cartList: [],
          allSelected: false,
          totalPrice: 0,
          selectedCount: 0
        })
        wx.showToast({
          title: '购物车已清空',
          icon: 'success'
        })
      }
    } catch (error) {
      console.error('清空购物车失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  },

  // 显示登录提示框
  showLoginModal() {
    wx.showModal({
      title: '提示',
      content: '请先登录后再查看购物车',
      confirmText: '去登录',
      success(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/login/login'
          })
        }
      }
    })
  },

  // 加载购物车数据
  async loadCartData() {
    try {
      this.setData({ loading: true })
      
      // 检查登录状态
      const token = wx.getStorageSync('token')
      if (!token) {
        this.setData({
          cartList: [],
          allSelected: false,
          totalPrice: 0,
          selectedCount: 0,
          loading: false
        })
        this.showLoginModal()
        return
      }

      // 先检查购物车状态
      await api.checkCartItems()
      const res = await api.getCart()
      
      if (res.success) {
        // 过滤掉不可用的商品
        const cartList = res.data
          .filter(item => item.isAvailable)
          .map(item => ({
            id: item.id,
            productId: item.product.id,
            name: item.product.name,
            price: item.product.price,
            image: item.product.imageUrl,
            quantity: item.quantity,
            selected: false
          }))
        
        this.setData({ 
          cartList,
          loading: false
        })
        this.updateTotalPrice()
        this.checkAllSelected()

        // 如果购物车为空，显示提示
        if (cartList.length === 0) {
          wx.showToast({
            title: '购物车暂无可用商品',
            icon: 'none'
          })
        }
      } else {
        throw new Error(res.message || '加载失败')
      }
    } catch (error) {
      console.error('加载购物车失败:', error)
      if (error.message === '请先登录' || error.message === '登录已过期') {
        this.setData({
          cartList: [],
          allSelected: false,
          totalPrice: 0,
          selectedCount: 0
        })
        // 如果是从登录页返回，不显示登录提示
        const pages = getCurrentPages()
        const prevPage = pages[pages.length - 2]
        if (!prevPage || prevPage.route !== 'pages/login/login') {
          this.showLoginModal()
        }
      } else {
        wx.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      }
    } finally {
      this.setData({ loading: false })
    }
  },

  // 切换商品选中状态
  toggleSelect(e) {
    const { id } = e.currentTarget.dataset
    const { cartList } = this.data
    const index = cartList.findIndex(item => item.id === id)
    
    if (index > -1) {
      cartList[index].selected = !cartList[index].selected
      this.setData({ cartList })
      this.updateTotalPrice()
      this.checkAllSelected()
    }
  },

  // 切换全选状态
  toggleSelectAll() {
    const { cartList, allSelected } = this.data
    const newAllSelected = !allSelected
    
    cartList.forEach(item => {
      item.selected = newAllSelected
    })
    
    this.setData({
      cartList,
      allSelected: newAllSelected
    })
    this.updateTotalPrice()
  },

  // 检查是否全部选中
  checkAllSelected() {
    const { cartList } = this.data
    const allSelected = cartList.length > 0 && cartList.every(item => item.selected)
    this.setData({ allSelected })
  },

  // 增加商品数量
  async increaseQuantity(e) {
    const { id } = e.currentTarget.dataset
    const { cartList } = this.data
    const index = cartList.findIndex(item => item.id === id)
    
    if (index > -1) {
      try {
        const res = await api.updateCart({
          productId: cartList[index].productId,
          quantity: cartList[index].quantity + 1
        })

        if (res.success) {
          cartList[index].quantity += 1
          this.setData({ cartList })
          this.updateTotalPrice()
        } else {
          wx.showToast({
            title: res.message || '更新失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('更新购物车失败:', error)
        wx.showToast({
          title: '更新失败',
          icon: 'none'
        })
      }
    }
  },

  // 减少商品数量
  async decreaseQuantity(e) {
    const { id } = e.currentTarget.dataset
    const { cartList } = this.data
    const index = cartList.findIndex(item => item.id === id)
    
    if (index > -1 && cartList[index].quantity > 1) {
      try {
        const res = await api.updateCart({
          productId: cartList[index].productId,
          quantity: cartList[index].quantity - 1
        })

        if (res.success) {
          cartList[index].quantity -= 1
          this.setData({ cartList })
          this.updateTotalPrice()
        } else {
          wx.showToast({
            title: res.message || '更新失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('更新购物车失败:', error)
        wx.showToast({
          title: '更新失败',
          icon: 'none'
        })
      }
    }
  },

  // 直接修改商品数量
  async updateQuantity(e) {
    const { id } = e.currentTarget.dataset
    let quantity = parseInt(e.detail.value)
    const { cartList } = this.data
    const index = cartList.findIndex(item => item.id === id)
    
    if (index > -1) {
      // 确保数量至少为1
      quantity = quantity < 1 ? 1 : quantity
      
      try {
        const res = await api.updateCart({
          productId: cartList[index].productId,
          quantity: quantity
        })

        if (res.success) {
          cartList[index].quantity = quantity
          this.setData({ cartList })
          this.updateTotalPrice()
        } else {
          wx.showToast({
            title: res.message || '更新失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('更新购物车失败:', error)
        wx.showToast({
          title: '更新失败',
          icon: 'none'
        })
      }
    }
  },

  // 删除商品
  async deleteItem(e) {
    const { id } = e.currentTarget.dataset
    const { cartList } = this.data
    const item = cartList.find(item => item.id === id)
    
    if (!item) {
      wx.showToast({
        title: '商品不存在',
        icon: 'none'
      })
      return
    }
    
    wx.showModal({
      title: '提示',
      content: '确定要删除这个商品吗？',
      success: async (modalRes) => {
        if (modalRes.confirm) {
          wx.showLoading({
            title: '删除中...',
            mask: true
          })
          
          try {
            // 先检查购物车状态
            await api.checkCartItems()
            
            // 使用购物车项ID删除
            const res = await api.removeFromCart(id)
            
            if (res.success) {
              // 从本地数据中移除商品
              const newCartList = this.data.cartList.filter(item => item.id !== id)
              this.setData({ 
                cartList: newCartList
              })
              this.updateTotalPrice()
              this.checkAllSelected()
              
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
            } else {
              throw new Error(res.message || '删除失败')
            }
          } catch (error) {
            console.error('删除购物车商品失败:', error)
            if (error.message === '购物车中不存在该商品') {
              // 如果后端返回商品不存在，也从本地移除该商品
              const newCartList = this.data.cartList.filter(item => item.id !== id)
              this.setData({ 
                cartList: newCartList
              })
              this.updateTotalPrice()
              this.checkAllSelected()
              
              wx.showToast({
                title: '商品已被删除',
                icon: 'none'
              })
            } else {
              wx.showToast({
                title: error.message || '删除失败',
                icon: 'none'
              })
            }
          } finally {
            wx.hideLoading()
          }
        }
      }
    })
  },

  // 去结算
  checkout() {
    const selectedItems = this.data.cartList.filter(item => item.selected);
    if (selectedItems.length === 0) {
      wx.showToast({
        title: '请选择要结算的商品',
        icon: 'none'
      });
      return;
    }

    // 将选中的商品信息存储到本地
    wx.setStorageSync('checkoutItems', selectedItems);

    // 跳转到结算页面
    wx.navigateTo({
      url: '/pages/order/checkout/checkout?from=cart'
    });
  },

  // 更新总价
  updateTotalPrice() {
    const { cartList } = this.data
    let totalPrice = 0
    let selectedCount = 0

    cartList.forEach(item => {
      if (item.selected) {
        totalPrice += item.price * item.quantity
        selectedCount += item.quantity
      }
    })

    this.setData({
      totalPrice: Number(totalPrice.toFixed(2)),
      selectedCount
    })
  },

  // 跳转到商品详情
  goToProduct(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/product/product?id=${id}`
    })
  }
})
